//
//  AppDelegate+AppService.m
//  SafeEatDemo
//
//  Created by bob on 2017/9/1.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "AppDelegate+AppService.h"
#import "NetStatuesListening.h"
#import "LoginStatuesModel.h"
#import "LoginViewController.h"
#import "RootNavigationController.h"
#import "HomeViewController.h"
#import "TB_FMDBManager.h"

@implementation AppDelegate (AppService)

#pragma mark ————— 初始化服务 —————
-(void)initService{
    
   
    
    //网络状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkStateChange:)
                                                 name:KNotificationNetWorkStateChange
                                               object:nil];
}

#pragma mark-获取IP
-(void)GetIP
{
    //测试环境时不需要调接口获取IP
    if([ReqUrl isEqualToString:@"http://erptest.zgfangxin.com/"] || [ReqUrl isEqualToString:@"http://192.168.1.97:8080"]){
        
        [self ConfigueNetRequest:nil];
        return;
    }
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/apiCheck.json" andrequestTime:5 andParams:@{@"version":kApplication.appVersion} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        if (responseStatus==1) {
            
            SetLoadIP(responseObject[@"data"][@"domain"]);
            
            [self ConfigueNetRequest:responseObject[@"data"][@"domain"]];
            
        }else{
            SetLoadIP(@"");
            
            [self ConfigueNetRequest:nil];
        }
    }];
}

#pragma mark ————— 初始化用户系统 —————
-(void)initUserManager{
    
    if ([LoginStatuesModel getUserToken].length>0) {
        //已经登录
        HomeViewController *homeVC=[HomeViewController new];
        
       NSInteger type= [LoginStatuesModel getUserType];
        
        homeVC.Utype=type;
   
        RootNavigationController *nav=[[RootNavigationController alloc]initWithRootViewController:homeVC];
        
        self.window.rootViewController=nav;
        
    }else{
        
        //未登录
        LoginViewController *loginVC=[LoginViewController new];
        
        RootNavigationController *nav=[[RootNavigationController alloc]initWithRootViewController:loginVC];
        self.window.rootViewController=nav;
    }

}

#pragma mark-初始化键盘

-(void)ConfigKeyBoard
{
    [IQKeyboardManager sharedManager].enable=YES;
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside=YES;
    
    [IQKeyboardManager sharedManager].enableAutoToolbar=NO;
    
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField=15.0f;
}


#pragma mark ————— 网络状态变化 —————
- (void)netWorkStateChange:(NSNotification *)notification
{
    BOOL isNetWork = [notification.object boolValue];
    
    if (isNetWork) {//有网络

        [MBProgressHUD showTopTipMessage:@"网络恢复正常" isWindow:YES];
        
    }else {//登陆失败加载登陆页面控制器
        [MBProgressHUD showTopTipMessage:@"网络状态不佳" isWindow:YES];
    }

}


#pragma mark ————— 网络状态监听 —————
- (void)monitorNetworkStatus
{
    // 网络状态改变一次, networkStatusWithBlock就会响应一次
    [NetStatuesListening networkStatusWithBlock:^(PPNetworkStatusType networkStatus) {
        
        switch (networkStatus) {
                // 未知网络
            case PPNetworkStatusUnknown:
                NSLog(@"网络环境：未知网络");
                // 无网络
                break;
                
            case PPNetworkStatusNotReachable:
                NSLog(@"网络环境：无网络");
                KPostNotification(KNotificationNetWorkStateChange, @NO);
                break;
                // 手机网络
            case PPNetworkStatusReachableViaWWAN:
                NSLog(@"网络环境：手机自带网络");
                // 无线网络
            case PPNetworkStatusReachableViaWiFi:
                NSLog(@"网络环境：WiFi");
//                KPostNotification(KNotificationNetWorkStateChange, @YES);
                break;
        }
        
    }];
    
}


-(void)ConfigueNetRequest:(NSString*)IpStr;
{
    YTKNetworkConfig *config=[YTKNetworkConfig sharedConfig];
    
//    NSString*Str=GetLoadIP;

    if (IpStr.length==0) {
        
        config.baseUrl=ReqUrl;
    }else{

        config.baseUrl=IpStr;
    }
    
//    config.baseUrl=ReqUrl;
//    config.cdnUrl=ReqUrl;

}

//初始化数据库
-(void)initBaseData
{
    [TB_FMDBManager shareDataBase];
    
}

-(void)intitWithBugly
{

//    [Bugly startWithAppId:BuglyAppID config:nil];
}

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}


-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}


-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}


@end
